package com.qingfeng.medical.biz.auth.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qingfeng.medical.base.handler.GeneralAuthException;
import com.qingfeng.medical.base.result.ResultCodeEnum;
import com.qingfeng.medical.biz.auth.dao.SysUserMapper;
import com.qingfeng.medical.biz.auth.dao.SysUserRoleMapper;
import com.qingfeng.medical.biz.auth.domain.dto.SysUserQueryDTO;
import com.qingfeng.medical.biz.auth.domain.entity.SysUser;
import com.qingfeng.medical.biz.auth.domain.entity.SysUserRole;
import com.qingfeng.medical.biz.auth.domain.excel.SysUserExcelVo;
import com.qingfeng.medical.biz.auth.domain.vo.RouterVo;
import com.qingfeng.medical.biz.auth.listener.UserVoExcelListener;
import com.qingfeng.medical.biz.auth.mq.producer.RabbitSendMsg;
import com.qingfeng.medical.biz.auth.service.SysMenuService;
import com.qingfeng.medical.biz.auth.service.SysUserService;
import com.qingfeng.medical.biz.file.service.FileService;
import com.qingfeng.medical.biz.information.domain.enums.DoctorPositionEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author 清风学Java
 * @version 1.0.0
 * @date 2023/4/2
 */
@Transactional(rollbackFor = GeneralAuthException.class)
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysMenuService sysMenuService;
    @Autowired
    private FileService fileService;
    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;
    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private RabbitSendMsg rabbitSendMsg;

    /**
     * 分页查询用户信息
     *
     * @param pageParam
     * @param userQueryVo
     * @return
     */
    @Override
    public IPage<SysUser> selectPage(Page<SysUser> pageParam, SysUserQueryDTO userQueryVo) {
        return sysUserMapper.selectPage(pageParam, userQueryVo);
    }

    /**
     * 更新用户状态
     *
     * @param id
     * @param status
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        SysUser sysUser = sysUserMapper.selectById(id);
        sysUser.setStatus(status);
        sysUserMapper.updateById(sysUser);
    }

    /**
     * 根据用户名称查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public SysUser getByUsername(String username) {
        return sysUserMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
        );
    }

    /**
     * 获取用户信息
     *
     * @param username
     * @return
     */
    @Override
    public Map<String, Object> getUserInfo(String username) {
        Map<String, Object> result = new HashMap<>(16);
        SysUser sysUser = this.getByUsername(username);

        //根据用户id获取菜单权限值
        List<RouterVo> routerVoList = sysMenuService.findUserMenuList(sysUser.getId());
        //根据用户id获取用户按钮权限
        List<String> permsList = sysMenuService.findUserPermsList(sysUser.getId());

        result.put("name", sysUser.getName());
        result.put("avatar", sysUser.getHeadUrl());
        //当前权限控制使用不到，我们暂时忽略
        result.put("roles", new HashSet<>());
        result.put("buttons", permsList);
        result.put("routers", routerVoList);
        return result;
    }

    @Override
    public void removeByUserId(Long id) {
        // 删除用户的时候，要将头像一并删除
        Optional.ofNullable(baseMapper.selectById(id).getHeadUrl())
                .ifPresent(headUrl -> fileService.removeFile(headUrl));

        baseMapper.deleteById(id);

        // 删除用户和角色的关系
        sysUserRoleMapper.delete(
                new LambdaQueryWrapper<SysUserRole>()
                        .eq(SysUserRole::getUserId, id)
        );
    }

    /**
     * 导出医院信息用户模板
     *
     * @param response
     */
    @Override
    public void exportUserTemplate(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //设置URLEncoder.encode可以解决中文乱码问题   这个和EasyExcel没有关系
            response.setHeader("Content-Disposition",
                    "attachment;filename=" +
                            URLEncoder.encode("医院用户信息模板", "UTF-8") +
                            ".xlsx");

            // 调用方法实现写操作
            EasyExcel.write(response.getOutputStream(), SysUserExcelVo.class)
                    .sheet("医院用户信息列表")
                    .doWrite(Collections.emptyList());
        } catch (Exception e) {
            throw new GeneralAuthException(ResultCodeEnum.FAIL.getCode(), "导出模板失败，请稍后再试！");
        }
    }

    /**
     * 导出医院用户信息
     *
     * @param response
     */
    @Override
    public void exportUser(HttpServletResponse response) {
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //设置URLEncoder.encode可以解决中文乱码问题   这个和EasyExcel没有关系
            response.setHeader("Content-Disposition",
                    "attachment;filename=" +
                            URLEncoder.encode("医院用户信息模板", "UTF-8") +
                            ".xlsx");

            // 查询所有的用户信息
            List<SysUser> sysUsers = baseMapper.selectList(null);
            List<SysUserExcelVo> userList = Collections.emptyList();
            if (CollUtil.isNotEmpty(sysUsers)) {
                userList = sysUsers
                        .stream()
                        .map(u -> SysUserExcelVo.builder()
                                .name(u.getName())
                                .username(u.getUsername())
                                .password(u.getPassword())
                                .phone(u.getPhone())
                                .build()
                        )
                        .collect(Collectors.toList());
            }

            // 调用方法实现写操作
            EasyExcel.write(response.getOutputStream(), SysUserExcelVo.class)
                    .sheet("医院用户信息列表")
                    .doWrite(userList);
        } catch (Exception e) {
            throw new GeneralAuthException(ResultCodeEnum.FAIL.getCode(), "导出模板失败，请稍后再试！");
        }
    }

    /**
     * 导入医院用户信息
     *
     * @param file
     */
    @Override
    public void importUser(MultipartFile file) {
        try {
            EasyExcel.read(
                            file.getInputStream(),
                            SysUserExcelVo.class,
                            new UserVoExcelListener(
                                    this,
                                    rabbitSendMsg,
                                    objectMapper
                            )
                    ).sheet()
                    .doRead();
        } catch (IOException e) {
            throw new GeneralAuthException(ResultCodeEnum.FAIL.getCode(), "导入医院用户信息失败，请稍后重试");
        }
    }

    /**
     * 查询医师用户基础信息
     * @param sysUserPage
     * @param username
     * @param position
     * @return
     */
    @Override
    public IPage<SysUser> selectUserPage(Page<SysUser> sysUserPage, String username, DoctorPositionEnum position) {
        return baseMapper.selectUserPage(sysUserPage, username, position);
    }
}
